package com.easy.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easy.common.api.CommonResult;
import com.easy.common.exception.Asserts;
import com.easy.domain.*;
import com.easy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.mapper.NoteMapper;

/**
 * @author 风亦未止
 * @date 2021/9/22 16:21
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements NoteService {
    @Autowired
    private NoteMapper noteMapper;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private NoteImgsService noteImgsService;
    @Autowired
    private NoteCommentsService noteCommentsService;
    @Autowired
    private NoteLikeService noteLikeService;
    @Autowired
    private UserService userService;

    @Override
    public CommonResult release(String desc, String[] imgUrl,Integer type) {
        String sessionId = httpSession.getId();
        User user = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(user)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        Note note = new Note();
        note.setDesc(desc);
        note.setOpenid(user.getOpenid());
        note.setType(type);
        Long insert = noteMapper.saveNote(note);
        if (insert > 0) {
            if (imgUrl.length == 0) {
                //没有图片
                return CommonResult.success(null);
            }
            //有图片，获取最近插入的小纸条的id
            Long id = note.getId();
            //保存图片
            for (String img : imgUrl) {
                NoteImgs noteImg = new NoteImgs();
                noteImg.setNoteId(id);
                noteImg.setImgUrl(img);
                noteImgsService.save(noteImg);
            }
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult comment(Long id, String desc) {
        String sessionId = httpSession.getId();
        User user = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(user)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        Note note = noteMapper.selectById(id);
        if (ObjectUtil.isNull(note)) {
            return CommonResult.success(null, "该小纸条不存在或已经被删除啦~");
        }
        NoteComments noteComments = new NoteComments();
        noteComments.setComment(desc);
        noteComments.setNoteId(note.getId());
        noteComments.setNickName(user.getNickName());
        noteComments.setOpenid(user.getOpenid());
        boolean save = noteCommentsService.save(noteComments);
        if (save) {
            return CommonResult.success(null, "评论成功！");
        }
        return CommonResult.failed("服务器出现了一些小问题，请稍等~");

    }

    @Override
    public CommonResult like(Long id) {
        String sessionId = httpSession.getId();
        User user = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(user)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        Note note = noteMapper.selectById(id);
        if (ObjectUtil.isNull(note)) {
            return CommonResult.success(null, "该小纸条不存在或已经被删除啦~");
        }
        NoteLike one = noteLikeService.lambdaQuery().eq(NoteLike::getOpenid, user.getOpenid()).eq(NoteLike::getNoteId, id).one();
        if (ObjectUtil.isNotEmpty(one)) {
            boolean b = noteLikeService.removeById(one);
            if (b) {
                return CommonResult.success(null, "取消成功！");
            }
            return CommonResult.failed("服务器出现了一些小问题，请稍等~");
        }
        NoteLike noteLike = new NoteLike();
        noteLike.setOpenid(user.getOpenid());
        noteLike.setNoteId(id);
        noteLike.setNickName(user.getNickName());
        boolean save = noteLikeService.save(noteLike);
        if (save) {
            return CommonResult.success(null, "点赞成功！");
        }
        return CommonResult.failed("服务器出现了一些小问题，请稍等~");
    }

    @Override
    public CommonResult<List<NoteVO>> getAll(int type) {
        List<Note> notes = lambdaQuery().eq(Note::getType,type).orderByDesc(Note::getCreateTime).list();
//        List<Note> notes = noteMapper.selectList(new QueryWrapper<>());
        List<NoteVO> noteVOList = new ArrayList<>();
        for (Note note : notes) {
            Long noteId = note.getId();
            Date createTime = note.getCreateTime();
            String openid = note.getOpenid();
            String desc = note.getDesc();
            User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
            List<NoteLike> likeList = noteLikeService.lambdaQuery().eq(NoteLike::getNoteId, noteId).list();
            List<NoteImgs> imgsList = noteImgsService.lambdaQuery().eq(NoteImgs::getNoteId, noteId).list();
            List<NoteComments> commentsList = noteCommentsService.lambdaQuery().eq(NoteComments::getNoteId, noteId).list();
            NoteVO noteVO = new NoteVO();
            String nickName = user.getNickName();
            String avatarUrl = user.getAvatarUrl();
            //System.out.println(user);
            noteVO.setId(noteId);
            noteVO.setOpenid(openid);
            noteVO.setAvatarUrl(avatarUrl);
            noteVO.setCommentsList(commentsList);
            noteVO.setCreateTime(createTime);
            noteVO.setDesc(desc);
            noteVO.setNoteImgs(imgsList);
            noteVO.setNoteLikes(likeList);
            noteVO.setNickName(nickName);
            noteVOList.add(noteVO);
        }
        return CommonResult.success(noteVOList);
    }

    @Override
    public CommonResult getMyAll(int type) {
        String sessionId = httpSession.getId();
        User loginUser = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(loginUser)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        String loginUserOpenid = loginUser.getOpenid();
        List<Note> notes = lambdaQuery().eq(Note::getType,type).eq(Note::getOpenid,loginUserOpenid).orderByDesc(Note::getCreateTime).list();
        List<NoteVO> noteVOList = new ArrayList<>();
        for (Note note : notes) {
            Long noteId = note.getId();
            Date createTime = note.getCreateTime();
            String openid = note.getOpenid();
            String desc = note.getDesc();
            User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
            List<NoteLike> likeList = noteLikeService.lambdaQuery().eq(NoteLike::getNoteId, noteId).list();
            List<NoteImgs> imgsList = noteImgsService.lambdaQuery().eq(NoteImgs::getNoteId, noteId).list();
            List<NoteComments> commentsList = noteCommentsService.lambdaQuery().eq(NoteComments::getNoteId, noteId).list();
            NoteVO noteVO = new NoteVO();
            String nickName = user.getNickName();
            String avatarUrl = user.getAvatarUrl();
//            System.out.println(user);
            noteVO.setId(noteId);
            noteVO.setOpenid(openid);
            noteVO.setAvatarUrl(avatarUrl);
            noteVO.setCommentsList(commentsList);
            noteVO.setCreateTime(createTime);
            noteVO.setDesc(desc);
            noteVO.setNoteImgs(imgsList);
            noteVO.setNoteLikes(likeList);
            noteVO.setNickName(nickName);
            noteVOList.add(noteVO);
        }
        return CommonResult.success(noteVOList);
    }

    @Override
    public CommonResult remove(int noteId) {
        String sessionId = httpSession.getId();
        User loginUser = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(loginUser)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        Note note = noteMapper.selectById(noteId);
        if (ObjectUtil.isNull(note)) {
            return CommonResult.success(null, "该小纸条不存在或已经被删除啦~");
        }
        int i = noteMapper.deleteById(noteId);
        noteLikeService.remove(new QueryWrapper<NoteLike>().eq(NoteLike.COL_NOTE_ID,noteId));
        noteImgsService.remove(new QueryWrapper<NoteImgs>().eq(NoteImgs.COL_NOTE_ID,noteId));
        noteCommentsService.remove(new QueryWrapper<NoteComments>().eq(NoteComments.COL_NOTE_ID,noteId));
        if (i>0){
            return CommonResult.success(null, "删除成功！");
        }
        return CommonResult.success(null, "删除失败！");
    }

    @Override
    public CommonResult getAllList(int type) {
        List<NoteVO> allList = noteMapper.getAllList(type);
        return CommonResult.success(allList);
    }

    @Override
    public CommonResult getMyAllList(int type) {
        String sessionId = httpSession.getId();
        User loginUser = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isEmpty(loginUser)) {
            Asserts.fail("登录信息已失效，请重新登录！");
            return null;
        }
        String loginUserOpenid = loginUser.getOpenid();
        List<NoteVO> allList = noteMapper.getAllList(type);
        List<NoteVO> collect = allList.stream().filter(noteVO -> noteVO.getOpenid().equals(loginUserOpenid)).collect(Collectors.toList());
        return CommonResult.success(collect);
    }

}

